package com.etong.citymap.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.etong.citymap.bean.ImageBean;
import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.impl.AppendixDaoImp;
import com.etong.citymap.db.impl.SentenceDaoImp;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.module.AppendixBean;
import com.etong.citymap.module.Image;
import com.etong.citymap.module.SentenceBean;
import com.etong.citymap.util.Configure;
import com.etong.citymap.util.Status;
import com.etong.citymap.util.StringUtil;
import com.etong.citymap.util.log.LogDetailUtil;
import com.etong.citymap.util.log.LogUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 感觉这个是现在在用的
 */
public class UploadSerivice1 extends Service {

	private List<SentenceBean> list;
	private SentenceDaoImp sentenceDaoImp = new SentenceDaoImp(UploadSerivice1.this);
	private AppendixDaoImp appendixDaoImp = new AppendixDaoImp(UploadSerivice1.this);
	private String Fjname ;
	/* private int dateerror=1;
 private int neterror=2;
 private int servererror=3;*/
	private int prjid;
	private Thread thread;
	private ImageBean[] ImageList;
	private CityApplication cityApplication;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		cityApplication = (CityApplication)getApplication();
	}
	@Override
	public void onDestroy() {
		LogDetailUtil.e("UploadSerivice1的onDestroy被调用！！！");
		stopSelf();
		super.onDestroy();
		if(!CityApplication.realLogout){
			// 再次拉起service
			stopForeground(true);
			Intent intent = new Intent();
			intent.setClass(this, UploadSerivice1.class);
			this.startService(intent);
		}
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		//开启线程上传数据
		cityApplication.setSave(true);
		thread=new Thread(new uploadStread());
		thread.start();

	}
	/**
	 * 线程执行
	 * @author Administrator
	 *
	 */
	public class uploadStread implements Runnable{

		@Override
		public void run() {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e1) {
				LogUtil.e(e1);
			}
			while(true){
				while(cityApplication.isSave()){
					try{
						SentenceDaoImp sentenceDaoImp=new SentenceDaoImp(UploadSerivice1.this);
						list=sentenceDaoImp.rawQuery("select * from sentence where SaveState=? and uploadState>=? and uploadSum<=? and superid=?", new String[]{String.valueOf(Status.SaveState_t1),String.valueOf(0),String.valueOf(Configure.uploadSum),cityApplication.getUserId()});
						Log.i("System.out.p", "记录数：" + list.size() + "  userId=" + cityApplication.getUserId());
						if(list.size()>0 && StringUtil.IsNotNull(cityApplication.getUserId())){
							Log.i("System.out.p", String.valueOf(list.size()));
							Log.i("System.out.p", "进入上传");
							check(list);
							Thread.sleep(6000);
						}else{
							Log.i("System.out.p", "没有要上传的数据");
							cityApplication.setSave(false);
							Thread.sleep(1000);

						}
					}catch(Exception e){
						LogUtil.e(e);

					}
				}

				try {
					Log.i("System.out.p", "进入休眠状态");
					Thread.sleep(60000);
					cityApplication.setSave(true);
				} catch (InterruptedException e) {
					LogUtil.e(e);
				}	

			}
		}

	}


	private void check(List<SentenceBean> list) {
		Log.i("System.out.p", "进入check");
		if(list.size()>0){
			for(SentenceBean s:list){
				Log.i("System.out.p", s.getPosition());
				Log.i("System.out.p", String.valueOf(s.getId()));
				List<AppendixBean> appendixBeans = appendixDaoImp.rawQuery("select * from appendix where caseid=?", new String[]{String.valueOf(s.getId())});
				if(appendixBeans!=null){
					Log.i("System.out.p", "记录数：" + appendixBeans.size());
					ImageList=new ImageBean[appendixBeans.size()];
					for(int i=0;i<ImageList.length;i++){
						ImageList[i] = new ImageBean();
						ImageList[i].setIsSelect(true);
						ImageList[i].setPathname(appendixBeans.get(i).getPath());
					}

				}

				if (appendixBeans.size() > 0) {
					Fjname="";
					for (int i = 0; i < ImageList.length; i++) {
						if (ImageList[i].isIsSelect()) {
							Fjname += ImageList[i].getPathname() + ",";
						}
					}

					Log.i("System.out.p", "Fjname="+Fjname);
					upload(s);

				} else{

					s.setUploadState(Status.ERORR_01000);
					s.setUploadSum(s.getUploadSum()+1);
					sentenceDaoImp.update(s);
					Log.i("System.out.p", "数据不合法");
					Intent intent=new Intent("android.intent.action.refresh");
					sendBroadcast(intent);
				}


			}
		}
	}

	private void upload(SentenceBean sentenceBean) {
		Log.i("System.out.p", "进入upload");
		String url = "supervisor/ashx/WorkStartNew.ashx";
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("Prjid", sentenceBean.getPrjid());
		map.put("Prjcheckid", sentenceBean.getPrjcheckid()==null?"-1":sentenceBean.getPrjcheckid());
		map.put("Position", "芜湖县");
		map.put("Eventtype", sentenceBean.getEventtype());
		map.put("Bigclass", sentenceBean.getBigclass());
		map.put("Smallclass", sentenceBean.getSmallclass());
		map.put("Situation", sentenceBean.getSituation());
		String cache = Fjname.substring(0, Fjname.length() - 1);
		map.put("Fjname", cache);
		map.put("Flag", sentenceBean.getFlag() + "");
		map.put("Superid", cityApplication.getUserId() + "");
		map.put("Code", cityApplication.getUserCode() + "");
		/*map.put("Bgcode", sentenceBean.getBgcode());
		map.put("Objcode", sentenceBean.getObjcode());
		map.put("Communityid", sentenceBean.getCommunityid());
		map.put("Units", sentenceBean.getUnits());*/
		map.put("Xcoor", sentenceBean.getXcoor());
		map.put("Ycoor", sentenceBean.getYcoor());
		map.put("Bgcode", sentenceBean.getBgcode());
		map.put("Communityid", sentenceBean.getCommunityid());

		if(sentenceBean.getFlag()==Status.ProjectType_SB){
			map.put("shushi", "2");
		}else{
			map.put("shushi", sentenceBean.getShushi()+"");
		}
		
		if(sentenceBean.getFlag()==Status.ProjectType_HC){
			if(!"2".equals(sentenceBean.getEventtype())){
				map.put("Objcode", sentenceBean.getObjcode());
				map.put("Units", sentenceBean.getUnits());
				//url = "&bgcode=" + sentenceBean.getBgcode() + "&objcode=" + sentenceBean.get + "&communityid=" + bujian.ComId + "&units=" + bujian.Units + "&xcoor=" + GloabData.bujian.X + "&ycoor=" + GloabData.bujian.Y;
			}
		}
		
		//处理要上传的所有的文件
		Image[] images = new Image[ImageList.length];
		String path = Environment.getExternalStorageDirectory()	+ cityApplication.CameraPath;
		for(int i=0; i<ImageList.length; i++){
			ImageBean ib = ImageList[i];
			Image image = new Image(path+ "/"+ ib.getPathname(),ib.getPathname());
			images[i] = image;
		}
		
		LogDetailUtil.i("开始上传");
		try {
			String result = HttpSendData.SendWorkStat(url, map, "utf-8",images,cityApplication.getHTTPURL());
			if (StringUtil.IsNull(result)) {
				LogDetailUtil.i("上传案卷的服务器返回的值为null");
				if(sentenceBean.getUploadSum()+1>=Configure.uploadSum){
					sentenceBean.setUploadState(Status.ERORR_0102);
				}
				sentenceBean.setUploadSum(sentenceBean.getUploadSum()+1);
				sentenceDaoImp.update(sentenceBean);
			} else {
				LogDetailUtil.i("上传案卷的服务器返回的值:" + result);
				if(result.startsWith("-3")) {
					sentenceBean.setUploadState(Status.ERORR_101);
					sentenceBean.setUploadSum(sentenceBean.getUploadSum()+1);
					sentenceDaoImp.update(sentenceBean);
					Log.i("System.out.p", "服务器错误");
					Intent intent=new Intent("android.intent.action.refresh");
					sendBroadcast(intent);
				}else if(result.startsWith("-1")) {
					sentenceBean.setUploadState(Status.ERORR_101);
					sentenceBean.setUploadSum(sentenceBean.getUploadSum()+1);
					sentenceDaoImp.update(sentenceBean);
					Log.i("System.out.p", "服务器错误");
					Intent intent=new Intent("android.intent.action.refresh");
					sendBroadcast(intent);
				}else if(result.startsWith("-4")){
					cityApplication.setSave(false);
					thread.stop();
					onDestroy();
					Log.i("System.out.p", "相同用户登陆");
				}else if(result.startsWith("-2")) {
					sentenceBean.setUploadState(Status.ERORR_0101);
					sentenceBean.setUploadSum(sentenceBean.getUploadSum()+1);
					sentenceDaoImp.update(sentenceBean);
					Log.i("System.out.p", "数据不合法");
					Intent intent=new Intent("android.intent.action.refresh");
					sendBroadcast(intent);
				} else {
					Log.i("System.out.p", "数据上传成功");
					//prjid = Integer.valueOf(result);
					sentenceBean.setPrjid(result);
					sentenceBean.setSaveState(Status.SaveState_t2);
					sentenceBean.setUploadSum(sentenceBean.getUploadSum()+1);
					sentenceDaoImp.update(sentenceBean);
					ImageList=null;

					Log.i("System.out.p", "上传结束");
					Intent intent=new Intent("android.intent.action.refresh");
					sendBroadcast(intent);
					//updateImage(sentenceBean,ImageList);
				}
			}
		} catch (Exception e) {
			LogUtil.e(e);
		}
	}

}
